package com.lindroy.androidplayer.ui.collection

import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import com.lindroy.androidplayer.base.BaseLazyFragment
import com.lindroy.androidplayer.databinding.FragmentCollectionWebsitesBinding
import com.lindroy.androidplayer.logic.network.base.http.observeState
import com.lindroy.androidplayer.ui.adapter.CollectedWebsiteAdapter
import com.lindroy.androidplayer.ui.webview.WebViewFragment
import com.lindroy.androidplayer.utils.addSimpleDivider
import com.lindroy.androidplayer.utils.orZero
import com.lindroy.androidplayer.viewmodels.CollectedWebsitesViewModel

/**
 * @author Lin
 * @date 2022/2/20
 * @function 我的收藏-网址
 */
class CollectionWebsitesFragment : BaseLazyFragment<FragmentCollectionWebsitesBinding>() {

    private val viewModel by viewModels<CollectedWebsitesViewModel>()

    private val adapter by lazy { CollectedWebsiteAdapter(viewLifecycleOwner) }

    override fun FragmentCollectionWebsitesBinding.initView(savedInstanceState: Bundle?) {
        vm = viewModel
        rvWebsite.addSimpleDivider()
        rvWebsite.adapter = adapter
    }

    override fun FragmentCollectionWebsitesBinding.initListener() {
        viewModel.collectedWebsite.data.observeState(viewLifecycleOwner){
            onSuccess { list->
                adapter.setData(viewModel.transData(list))
            }
        }

        swipeRefreshLayout.setOnRefreshListener {
            viewModel.collectedWebsite.refresh()
        }
        viewModel.itemClickLiveData.observe(viewLifecycleOwner) {
            WebViewFragment.start(
                this@CollectionWebsitesFragment,
                it.id.orZero(),
                it.link.orEmpty(),
                it.name.orEmpty(),
                true
            )
        }
    }

    override fun lazyLoad() {
        viewModel.collectedWebsite.load()
    }

    override fun onRetryClick(view: View) {
        super.onRetryClick(view)
        viewModel.collectedWebsite.retry()
    }

}